<!-- subpkg_archive/form/index.vue -->
<script setup lang="ts">
import { ref } from 'vue'
import { addPatientApi, patientDetailApi, updatePatientApi } from '@/apis/patient'
import { onLoad } from '@dcloudio/uni-app';
import type { PatientParams } from '@/types/patient'

const formData = ref<PatientParams>({
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: 1,
})

const formRef = ref()
// 加载数据
// onLoad(() => {
//   console.log('form onLoad')
//   console.log(query?.id);
// })
// 使用 defineProps 接收地址参数
const props = defineProps<{ id: string }>()
async function getPatientDetail() {
  // 是否存在患者 ID
  if (!props.id) return
  // 有ID说明当前处于编辑状态，修改页面标题
  uni.setNavigationBarTitle({ title: '编辑患者' })

  // 患者详情接口
  const data = await patientDetailApi(props.id)

  // 渲染患者信息
  formData.value = data
}
getPatientDetail()

const onSwitchChange = (ev: any) => {
  // @ts-ignore
  formData.value.defaultFlag = ev.detail.value ? 1 : 0
}
// 校验规则
const rules = {
  name: {
    rules: [
      { required: true, errorMessage: '请填写患者姓名' },
      {
        pattern: '^[\u4e00-\u9fa5]{2,5}$',
        errorMessage: '患者姓名为2-5位中文',
      },
    ],
  },
  idCard: {
    rules: [
      { required: true, errorMessage: '请输入身份证号' },
      {
        pattern:
          '^[1-9]\\d{5}(?:18|19|20)\\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\\d|30|31)\\d{3}[\\dXx]$',
        errorMessage: '身份证号格式不正确',
      },
    ],
  },
  gender: {
    rules: [
      { required: true, errorMessage: '请勾选患者性别' },
      {
        // @ts-ignore
        validateFunction(rule, value, data, callback) {
          // 检测身份证号第17位是否为偶数
          if (data.idCard.slice(16, 17) % 2 !== value) {
            callback('选择的性别与身份号中性别不一致')
          }
          // 验证通过时返回 true
          return true
        },
      }
    ],
  },
}
// 提交
const submit = async () => {
  // 调用校验
  const data = await formRef.value.validate()

  // 110101198307212600
  // 110101196107145504
  // 11010119890512132X
  // 110101196501023433
  // 110101197806108758
  // 110101198702171378
  // 110101198203195893
  try {
    // 区分判断不同的接口调用 当id有值时候为编辑接口 否则为添加接口
    if (props.id) {
      await updatePatientApi(formData.value)
    } else {
      await addPatientApi(formData.value)
    }

    uni.showToast({
      title: props.id ? '修改成功' : '添加成功',
      // title: '添加成功',
      icon: 'none',
    })
    // 跳转到患者列表页面
    uni.navigateBack()
  } catch (error: any) {
    uni.showToast({
      title: error.message,
      icon: 'none',
    })
  }

}
</script>

<template>
  <scroll-page>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" :model-value="formData" ref="formRef" :rules="rules">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput placeholder-style="color: #C3C3C5; font-size: 32rpx" :styles="{ color: '#121826' }"
            :input-border="false" :clearable="false" placeholder="请填写真实姓名" v-model="formData.name" />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput placeholder-style="color: #C3C3C5; font-size: 32rpx" :styles="{ color: '#121826' }"
            :input-border="false" :clearable="false" placeholder="请填写身份证号" v-model="formData.idCard" />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <!-- uni-data-checkbox 选择器 -->
          <uni-data-checkbox v-model="formData.gender" selectedColor="#16C2A3" :localdata="[
            { text: '男', value: 1 },
            { text: '女', value: 0 },
          ]" />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="name">
          <view class="uni-switch">
            <switch :checked="formData.defaultFlag === 1 ? true : false" color="#20c6b2" style="transform: scale(0.7)"
              @change="onSwitchChange" />
          </view>
        </uni-forms-item>
        <button class="uni-button" @click="submit">保存</button>
      </uni-forms>
    </view>
  </scroll-page>
</template>

<style lang="scss">
@import './index.scss';
</style>
